<template>
  <div>
    <div class="content-item">
      <div v-if="editable">
        <span class="label">被检寝室：</span>
        <span>{{queryParams.roomInfo}}</span>
      </div>
      <div v-else>
        <span class="label">被检寝室：</span>
        <el-select v-model="queryParams.schoolAreaId"
                   placeholder="--校区--"
                   @change="cascade('campus')"
                   size="small">
          <el-option v-for="(item, index) in campus"
                     :key="index"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.campusId"
                   placeholder="--园区--"
                   @change="cascade('gardens')"
                   size="small">
          <el-option v-for="(item, index) in gardens"
                     :key="index"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.buildingId"
                   placeholder="--楼栋--"
                   @change="cascade('building')"
                   size="small">
          <el-option v-for="(item, index) in buildings"
                     :key="index"
                     :label="item.number + '栋' + item.unitNumber + '单元'"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.floorId"
                   placeholder="--楼层--"
                   @change="cascade('floor')"
                   size="small">
          <el-option v-for="(item, index) in floors"
                     :key="index"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.roomId"
                   placeholder="--房间--"
                   @change="cascade('room')"
                   size="small">
          <el-option v-for="(item, index) in rooms"
                     :key="index"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="g-mt10">
        <span class="label">检查日期：</span>
        <el-date-picker v-model="queryParams.date"
                        size="small"
                        style="width: 215px;"
                        :picker-options="date"
                        @change="changeDate"
                        :disabled="editable"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        type="date"
                        placeholder="选择检查日期">
        </el-date-picker>
      </div>
      <div class="g-mt10">
        <span class="label">星级检查：</span>
        <el-select v-model="queryParams.checkWorkId"
                   placeholder="请选择"
                   :disabled="editable"
                   @change="changeType"
                   size="small">
          <el-option v-for="(item, index) in checkWorkList"
                     :key="index"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="g-mt10">
        <p>寝室人员</p>
        <el-table :data="roomMerberInfo"
                  class="table-header-gray">
          <el-table-column label="学号"
                           prop="sn"></el-table-column>
          <el-table-column label="姓名"
                           prop="name"></el-table-column>
          <el-table-column label="性别"
                           :formatter="formatGender"
                           prop="gender"></el-table-column>
          <el-table-column label="学生类型"
                           prop="objectOrientedName"></el-table-column>
          <el-table-column label="学院"
                           prop="collegeName"></el-table-column>
          <el-table-column label="专业"
                           prop="majorName"></el-table-column>
          <el-table-column label="年级"
                           prop="gradeName"></el-table-column>
          <el-table-column label="班级"
                           prop="className"></el-table-column>
        </el-table>
      </div>
      <div class="g-mt10">
        <p>卫生检查&nbsp;&nbsp;&nbsp;&nbsp;平均得分&nbsp;{{avgScore | filterAvg}}&nbsp;&nbsp;&nbsp;<el-button size="small"
                     @click="addLog">+添加</el-button>
        </p>
        <el-table :data="logData"
                  class="table-header-gray">
          <el-table-column label="检查人"
                           prop="checkUserName"></el-table-column>
          <el-table-column v-for="(item, index) in logDataTitle"
                           :key="index"
                           :label="item.name"
                           :prop="item.name"></el-table-column>
          <el-table-column label="总分"
                           prop="score"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <span class="gtextlink"
                    @click="del(scope)">移除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="g-mt20">
        <el-button size="small"
                   @click="$router.go(-1)">返回</el-button>
        <el-button size="small"
                   type="primary"
                   :loading="saveLoading"
                   @click="submit">保存</el-button>
      </div>
      <dialog-new :detailShow="detailShow"
                  ref="dialogParent"
                  :rules="rules"
                  :handleClose="handleClose"
                  @handleConfirm="handleConfirm"
                  :formData="logDataTitle" />
    </div>
  </div>
</template>
<script>
import { listStudentByRoomAndDateUsingGET, saveOrUpdateRecordUsingPOST, listTitleAndScoreUsingGET, listWorkListUsingPOST, listSchoolAreaByUserUsingGET, listCampusBySchoolAreaIdAndUserUsingGET, listBuildingByCampusIdAndUserUsingGET, listFloorByBuildingIdUsingGET, listRoomByCollegeAndFloorUsingGET, updateViolationStatusUsingGET } from '@api/auto'
import { formatTool } from '@/tools/mixin'
// import { randomStr } from '@/tools/utils'
import dialogNew from './dialog'
export default {
  name: '',
  props: {
  },
  mixins: [formatTool],
  components: { dialogNew },
  data () {
    return {
      saveLoading: false,
      detailShow: false,
      editable: false,
      date: {
        disabledDate: time => {
          return time.getTime() > Date.now()
        }
      },
      queryParams: {
        date: null,
        healthRecordId: null,
        schoolAreaId: '',
        campusId: '',
        buildingId: '',
        floorId: '',
        roomId: '',
        checkWorkId: ''
      },
      // 校区
      campus: [],
      // 园区
      gardens: [],
      // 楼栋
      buildings: [],
      // 楼层
      floors: [],
      // 房间
      rooms: [],
      // 检查项目列表
      projects: [],
      checkWorkList: [],
      tableData: [],
      logData: [],
      logDataTitle: [],
      // 寝室成员信息
      roomMerberInfo: [],
      tempSanitation: [],
      healthRocordDetailDtoList: [],
      deleteIdList: [],
      rules: {
        checkUserName: [
          { required: true, message: '请输入检查人姓名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur' }
        ]
      },
      avgScore: null
    }
  },
  filters: {
    filterAvg: function (value) {
      if (isNaN(value)) {
        return ''
      } else {
        return value
      }
    }
  },
  watch: {
    logData: function (n, o) {
      let that = this
      let score = 0
      n.forEach(item => {
        score += item.score
      })
      that.avgScore = (score / n.length).toFixed(2)
    }
  },
  created () {
    this.$route.query.type === 'edit' ? this.editable = true : this.editable = false
    if (this.editable) {
      this.formBackfill()
    } else {
      this.queryParams.date = new Date()
    }
  },
  mounted () {
    this.listSchoolAreaByUserUsingGET()
    this.listWorkListUsingPOST()
    if (!this.editable) {
      this.listTitleAndScoreUsingGET(-1)
    }
  },
  methods: {
    cascade (type) {
      switch (type) {
        case 'campus':
          this.listCampusBySchoolAreaIdAndUserUsingGET()
          break
        case 'gardens':
          this.listBuildingByCampusIdAndUserUsingGET()
          break
        case 'building':
          this.listFloorByBuildingIdUsingGET()
          break
        case 'floor':
          this.listRoomByCollegeAndFloorUsingGET()
          break
        case 'room':
          this.changeRoom()
      }
    },
    // 用户根据登陆用户查询可以查看的校区
    listSchoolAreaByUserUsingGET () {
      listSchoolAreaByUserUsingGET()
        .then(res => {
          this.campus = res.data
        })
    },
    // 根据登陆用户查询指定校区下的园区
    listCampusBySchoolAreaIdAndUserUsingGET () {
      this.queryParams.campusId = null
      this.queryParams.buildingId = null
      this.queryParams.floorId = null
      this.queryParams.roomId = null
      this.buildings = []
      this.gardens = []
      this.floors = []
      this.rooms = []
      listCampusBySchoolAreaIdAndUserUsingGET(this.queryParams.schoolAreaId)
        .then(res => {
          this.gardens = res.data
        })
    },
    // 根据园区id和登陆用户查询管辖的楼栋
    listBuildingByCampusIdAndUserUsingGET () {
      this.queryParams.buildingId = null
      this.queryParams.floorId = null
      this.queryParams.roomId = null
      this.buildings = []
      this.floors = []
      this.rooms = []
      listBuildingByCampusIdAndUserUsingGET(this.queryParams.campusId)
        .then(res => {
          this.buildings = res.data
        })
    },
    // 根据楼栋查楼层
    listFloorByBuildingIdUsingGET () {
      this.queryParams.floorId = null
      this.queryParams.roomId = null
      this.floors = []
      this.rooms = []
      listFloorByBuildingIdUsingGET(this.queryParams.buildingId)
        .then(res => {
          this.floors = res.data
        })
    },
    // 根据楼层查房间
    listRoomByCollegeAndFloorUsingGET () {
      this.queryParams.roomId = null
      this.rooms = []
      listRoomByCollegeAndFloorUsingGET(this.queryParams.floorId, -1)
        .then(res => {
          this.rooms = res.data
        })
    },
    // 根据检查记录、寝室id查寝室人员
    listStudentByRoomAndDateUsingGET (recordId) {
      if (this.queryParams.roomId) {
        listStudentByRoomAndDateUsingGET(this.queryParams.roomId, new Date(this.queryParams.date).toString())
          .then(res => {
            this.roomMerberInfo = res.data
          })
      }
    },
    // 获取状态为进行中和已结束的星级寝室检查项
    listWorkListUsingPOST () {
      listWorkListUsingPOST()
        .then(res => {
          this.checkWorkList = res.data
        })
    },
    // 日期变化
    changeDate () {
      if (this.queryParams.roomId && this.queryParams.date && this.queryParams.checkWorkId) {
        this.updateViolationStatusUsingGET()
      }
    },
    // 检查项目变化
    changeType () {
      if (this.queryParams.roomId && this.queryParams.date && this.queryParams.checkWorkId) {
        this.updateViolationStatusUsingGET()
      }
    },
    // 所选房间变化
    changeRoom () {
      if (this.queryParams.roomId && this.queryParams.date && this.queryParams.checkWorkId) {
        this.updateViolationStatusUsingGET()
      }
    },
    addLog () {
      if (this.queryParams.roomId && this.queryParams.date && this.queryParams.checkWorkId) {
        this.detailShow = true
      } else {
        this.$message.warning('请先选择被检寝室、检查日期、星级检查')
      }
    },
    // 根据房间id,检查日期,检查id查询卫生记录
    updateViolationStatusUsingGET () {
      let that = this
      updateViolationStatusUsingGET(this.queryParams.roomId, new Date(this.queryParams.date).toString(), this.queryParams.checkWorkId)
        .then(res => {
          this.logData = (res.data && res.data.dataList) || []
          if (res.data && res.data.dataList) {
            this.queryParams.healthRecordId = this.logData[0].healthRecordId
          } else {
            this.queryParams.healthRecordId = -1
          }
          // if (res.data && res.data.dataList) {
          //   this.logData = res.data.dataList
          //   this.queryParams.healthRecordId = this.logData[0].healthRecordId
          // }
          that.listStudentByRoomAndDateUsingGET(this.queryParams.healthRecordId || -1)
          that.listTitleAndScoreUsingGET(this.queryParams.healthRecordId || -1)
        })
    },
    // 获取表头
    listTitleAndScoreUsingGET (id) {
      listTitleAndScoreUsingGET(id)
        .then(res => {
          this.logDataTitle = res.data || []
          if (!this.logDataTitle.length) {
            this.$alert('暂未配置检查工作项，不能进行卫生记录录入', '提示', {
              confirmButtonText: '返回',
              callback: action => {
                this.$router.go(-1)
              }
            })
          } else {
            this.logDataTitle = this.$lodash.orderBy(this.logDataTitle, ['order'], ['asc'])
            this.logDataTitle.forEach(item => {
              this.rules[item.name] = [
                { required: true, message: '请输入分数', trigger: 'blur' },
                { type: 'number', message: '分数必须为数字值' },
                { pattern: /^([1-9]\d*|0)(\.\d{1,2})?$/, message: '小数位保留两位，不能输入负数' }
              ]
            })
          }
        })
    },
    handleClose () {
      this.detailShow = false
    },
    // 计算总分
    computedScore (obj) {
      let temp = this.$lodash.cloneDeep(obj)
      delete temp.checkUserName
      let score = 0
      for (let i in temp) {
        score += obj[i]
      }
      score = this.$lodash.ceil(score, 2)
      console.log(typeof score)
      return score
    },
    // 卫生检查添加弹窗关闭
    handleConfirm (data) {
      let tempTable = this.$lodash.cloneDeep(data)
      tempTable.score = this.computedScore(tempTable)
      this.logData.push(tempTable)
      this.$refs.dialogParent.$refs.form.resetFields()
      this.detailShow = false
    },
    // 提交前处理healthRocordDetailDtoList
    handleHealth (arr) {
      let result = []
      arr.forEach(item => {
        if (!item.id) {
          let temp = this.$lodash.cloneDeep(item)
          let name = temp.checkUserName
          delete temp.checkUserName
          delete temp.score
          delete temp.id
          let obj = {
            checkUserName: name,
            score: this.computedScore(temp),
            checkData: temp
          }
          result.push(obj)
        }
      })
      return result
    },
    submit () {
      if (this.queryParams.roomId && this.queryParams.date && this.queryParams.checkWorkId && this.logData && this.logData.length) {
        let temp = this.handleHealth(this.logData)
        let obj = {
          checkWorkId: this.queryParams.checkWorkId,
          createDate: this.$moment(this.queryParams.date).format('YYYY-MM-DD'),
          healthRocordDetailDtoList: temp,
          deleteIdList: this.deleteIdList,
          roomId: this.queryParams.roomId
        }
        if (this.queryParams.healthRecordId) {
          obj.healthRecordId = this.queryParams.healthRecordId
        }
        this.saveLoading = true
        saveOrUpdateRecordUsingPOST(obj)
          .then(() => {
            this.$message.success('操作成功')
            this.saveLoading = false
            this.$router.go(-1)
          })
          .catch(() => {
            this.saveLoading = false
          })
      } else {
        this.$message.warning('被检寝室、检查日期、星级检查、卫生检查均为必填项')
      }
    },
    // 表单回填
    formBackfill () {
      let temp = JSON.parse(sessionStorage.sanitationDetail)
      this.queryParams.checkWorkId = temp.checkWorkId || -1
      this.queryParams.date = this.$moment(temp.checkDate).format('YYYY-MM-DD HH:mm:ss')
      this.logData = temp.dataList
      this.queryParams.roomId = temp.roomId
      this.queryParams.roomInfo = temp.roomInfo
      // this.roomMerberInfo = temp.studentList
      this.queryParams.healthRecordId = temp.id || -1
      // let a = null
      // let b = {}
      // a = this.handleTitle(temp.columns)
      // a.forEach(item => {
      //   b[item.name] = [
      //     { required: true, message: '请输入分数', trigger: 'blur' },
      //     { type: 'number', message: '分数必须为数字值' }
      //   ]
      // })
      // console.log(a, 2)
      // this.logDataTitle = this.handleTitle(temp.columns)
      // this.logDataTitle.forEach(item => {
      //   this.rules[item.name] = [
      //     { required: true, message: '请输入分数', trigger: 'blur' },
      //     { type: 'number', message: '分数必须为数字值' }
      //   ]
      // })
      // console.log(this.logDataTitle, 3)
      this.listTitleAndScoreUsingGET(this.queryParams.healthRecordId)
      this.updateViolationStatusUsingGET()
    },
    // 处理多余表头
    handleTitle (arr) {
      let temp = []
      arr.forEach(item => {
        if (item.name !== 'id' && item.name !== 'checkUserName' && item.name !== 'score') {
          temp.push(item)
        }
      })
      return temp
    },
    del (row) {
      console.log(row)
      // 通过id删除项
      this.$confirm('是否确认删除此行记录？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.row && row.row.id) {
          this.deleteIdList.push(row.row.id)
        }
        this.logData.splice(row.$index, 1)
      })
    }
  }
}
</script>
<style lang='less' scoped>
</style>
